<template>
  <div style="width: 100%;height: 100vh;display: flex;justify-content: center;align-items: center;">
    <div class="container">
    <div class="title">膀胱压力与尿量实时监控</div>

    <div class="data-container">
      <div class="data-section">
        <div class="data-label"> <text>📊</text> 膀胱压力 </div>
        <div
          :class="[
            'data-value',
            'pressure-value',
            pressure > 40 ? 'critical' : '',
          ]"
          id="pressure-value"
        >
          {{ pressure.toFixed(1) }}
        </div>
        <div class="unit">mmH<sub>2</sub>O</div>
      </div>

      <div class="data-grid">
        <div class="data-card flow-card">
          <div class="card-label">实时尿量</div>
          <div id="flow-value" class="card-value">{{
            realTimeVolume.toFixed(2)
          }}</div>
          <div class="unit">mL/s</div>
        </div>

        <div class="data-card volume-card">
          <div class="card-label">累计尿量</div>
          <div id="volume-value" class="card-value">{{
            totalVolume.toFixed(1)
          }}</div>
          <div class="unit">mL</div>
        </div>

        <div class="data-card pressure-card">
          <div class="card-label">压力上限</div>
          <div id="upper-limit" class="card-value">80</div>
          <div class="unit">mmH<sub>2</sub>O</div>
        </div>

        <div class="data-card limit-card">
          <div class="card-label">压力下限</div>
          <div id="lower-limit" class="card-value">20</div>
          <div class="unit">mmH<sub>2</sub>O</div>
        </div>

        <div class="data-card limit-card">
          <div class="card-label">机器码</div>
          <div id="machineCode" class="card-value">{{ machineCode }}</div>
        </div>

        <div class="data-card limit-card">
          <div class="card-label">识别号</div>
          <div id="machineId" class="card-value">{{ machineId }}</div>
        </div>

        <div class="data-card limit-card">
          <div class="card-label">数据3</div>
          <div id="value3" class="card-value">{{ value3.toFixed(2) }}</div>
        </div>

        <div class="data-card limit-card">
          <div class="card-label">数据4</div>
          <div id="value4" class="card-value">{{ value4.toFixed(2) }}</div>
        </div>
      </div>

      <div class="chart-container">
        <!-- 折线图-->
        <!-- <qiun-data-charts 
			type="line"
			:opts="chartOpts"
			:chartData="chartData"
		  /> -->

        <div id="main" style="width: 550px; height: 300px"></div>

        <!-- 柱状图-->
        <!--        <div class="chart">
          <div class="chart-line"></div>
          <div class="chart-data">
            <div
              v-for="(value, index) in pressureHistory"
              :key="index"
              class="chart-bar"
              :style="{ height: getBarHeight(value) }"
              :title="`压力: ${value.toFixed(1)} mmH₂O`"
            ></div>
          </div>
          <div class="chart-label">
            <text>-60s</text>
            <text>-45s</text>
            <text>-30s</text>
            <text>-15s</text>
            <text>当前</text>
          </div>
        </div> -->
      </div>
    </div>

    <div class="status-container">
      <div
        :class="['status', isServerConnected ? 'connected' : '']"
        id="status"
      >
        <div class="status-dot"></div>
        <text>{{ isServerConnected ? "服务器已连接" : "服务器未连接" }}</text>
      </div>
      <div
        :class="['status', isDataUpdated ? 'connected' : '']"
        id="update-status"
      >
        <div class="status-dot"></div>
        <text>{{ isDataUpdated ? "数据已更新" : "等待数据" }}</text>
      </div>
    </div>

    <div class="footer">
      <text>数据来源: ESP32传感器 | 服务器: 192.168.0.101:8080</text>
      <text>最后更新: {{ lastUpdate }}</text>
    </div>
  </div>
  </div>
</template>

<script setup>
import * as echarts from "echarts";
import { ref, onMounted, onBeforeUnmount, watch } from "vue";
import { getLatestMonitorData } from "@/api/sensorAPI.js";
import { useRoute } from "vue-router";
const route = useRoute();
// import {
// 	onLoad
// } from '@dcloudio/uni-app'

// 响应式数据
const pressure = ref(0);
const realTimeVolume = ref(0);
const totalVolume = ref(0);
const machineCode = ref("--");
const machineId = ref("--");
const value3 = ref(0);
const value4 = ref(0);
const pressureHistory = ref([]);
const volumeHistory = ref([]); // 新增：实时尿量历史数据
const maxHistory = 20;
const isServerConnected = ref(false);
const isDataUpdated = ref(false);
const lastUpdate = ref("--:--:--");
let fetchTimer = null; // 定时器句柄

// 图表配置
// const chartOpts = ref({
//   color: ["#3498db", "#27ae60"], // 蓝色表示压力，绿色表示尿量
//   padding: [15, 10, 25, 30], // 调整底部边距，为x轴标签留出空间
//   enableScroll: false,
//   legend: {
//     position: 'bottom' // 图例位置
//   },
//   xAxis: {
//     disableGrid: true,
//     itemCount: 5, // 显示5个时间点标签
//     labels: ['-60s', '-45s', '-30s', '-15s', '当前']
//   },
//   yAxis: {
//     gridType: "dash",
//     dashLength: 2
//   },
//   extra: {
//     line: {
//       type: "curve", // 曲线类型
//       width: 2,
//       activeType: "hollow"
//     }
//   }
// });

// 图表数据
// const chartData = ref({
//   categories: [],
//   series: [
//     {
//       name: "膀胱压力",
//       data: []
//     },
//     {
//       name: "实时尿量",
//       data: []
//     }
//   ]
// });

// 初始化历史数据
for (let i = 0; i < maxHistory; i++) {
  pressureHistory.value.push(0);
  volumeHistory.value.push(0); // 初始化尿量历史数据
}

// 更新压力值显示
function updatePressure(value) {
  pressure.value = value;
  // 阈值判断（40为临界值）
  if (value > 40) {
    pressure.value = value; // 触发响应式更新
  }
}

// 更新实时尿量
function updateFlow(value) {
  realTimeVolume.value = value;
}

// 更新累计尿量
function updateVolume(value) {
  totalVolume.value = value;
}

// 更新机器码（8位补0）
function updateMachineCode(value) {
  machineCode.value = Math.floor(value).toString().padStart(8, "0");
}

// 更新识别号（8位补0）
function updateMachineId(value) {
  machineId.value = Math.floor(value).toString().padStart(8, "0");
}

// 更新数据3
function updateValue3(value) {
  value3.value = value;
}

// 更新数据4
function updateValue4(value) {
  value4.value = value;
}

// 更新连接状态
function updateStatus(connected) {
  isServerConnected.value = connected;
}

// 更新数据状态（3秒后重置）
function updateDataStatus(updated) {
  isDataUpdated.value = updated;
  if (updated) {
    setTimeout(() => {
      isDataUpdated.value = false;
    }, 3000);
  }
}

// 更新图表
function updateChart() {
  // 生成时间标签（最近20个时间点）
  const categories = Array.from(
    {
      length: maxHistory,
    },
    (_, i) => {
      const secondsAgo = (maxHistory - i - 1) * 3; // 假设每3秒一个数据点
      return secondsAgo === 0 ? "当前" : `-${secondsAgo}s`;
    }
  );

  chartData.value = {
    categories,
    series: [
      {
        name: "膀胱压力",
        data: [...pressureHistory.value],
      },
      {
        name: "实时尿量",
        data: [...volumeHistory.value],
      },
    ],
  };
}

// 更新时间戳
function updateTimestamp() {
  const now = new Date();
  lastUpdate.value = now.toTimeString().substring(0, 8);
}

// 数据请求（使用API接口）
async function fetchData(deviceId) {
  // 使用传感器API获取最新数据
  const res = await getLatestMonitorData(deviceId);
  const data = res.data
  if (data && typeof data.pressure === "number") {
    // 更新核心数据
    updatePressure(data.pressure);
    updateFlow(data.realTimeVolume || 123);
    updateVolume(data.totalVolume || 123);
    updateMachineCode(data.machineCode || 123);
    updateMachineId(data.machineId || 123);
    updateValue3(data.value3 || 123);
    updateValue4(data.value4 || 123);

    // 更新历史记录
    pressureHistory.value.push(data.pressure);
    volumeHistory.value.push(data.realTimeVolume);

    if (pressureHistory.value.length > maxHistory) {
      pressureHistory.value.shift();
      volumeHistory.value.shift();
    }

    // 触发图表更新
    // updateChart();
    initCharts(data.pressure, data.realTimeVolume);
    updateStatus(true);
    updateDataStatus(true);
    updateTimestamp();
  }
}

// 生命周期：页面加载初始化
onMounted(() => {
  // fetchData(); // 首次加载
  // fetchTimer = setInterval(fetchData, 2000); // 定时轮询
  // updateChart(); // 初始化图表
  // initCharts();
  fetchData(route.query.deviceId); // 首次加载
  fetchTimer = setInterval(() => {
    fetchData(route.query.deviceId);
  }, 2000);
});

// onLoad((option) => {
// 	console.log(option)
// 	fetchData(option.deviceId); // 首次加载
// 	fetchTimer = setInterval(() => {
// 		fetchData(option.deviceId)
// 	}, 2000);
// 	// initCharts();
// })

// 生命周期：页面卸载清理
onBeforeUnmount(() => {
  clearInterval(fetchTimer); // 清除定时器
  clearChartTimer();
});

// 全局变量存储图表实例和数据
let myChart = null;
// 在chartData定义前添加生成时间标签的函数
const generateTimeLabels = (count) => {
  const labels = [];
  const now = new Date();

  // 生成count个时间标签，从当前时间往前推算
  for (let i = count - 1; i >= 0; i--) {
    const time = new Date(now.getTime() - i * 60000); // 每隔1分钟
    const hour = time.getHours().toString().padStart(2, "0");
    const minute = time.getMinutes().toString().padStart(2, "0");
    const second = time.getSeconds().toString().padStart(2, "0");
    labels.push(`${hour}:${minute}:${second}`);
  }

  return labels;
};

// 修改chartData中的categories
let chartData = {
  categories: generateTimeLabels(6), // 生成6个时间标签
  series1: [0, 0, 0, 0, 0, 0],
  series2: [0, 0, 0, 0, 0, 0],
  timer: null,
};

const initCharts = (data1, data2) => {
  // 基于准备好的dom，初始化echarts实例
  if (!myChart) {
    myChart = echarts.init(document.getElementById("main"));
  }
  // 绘制图表
  myChart.setOption({
    legend: {
      data: ["膀胱压力", "实时尿量"],
      right: 0,
      top: 0,
      orient: "horizontal",
      itemGap: 16,
      icon: "roundRect",
      itemWidth: 14,
      itemHeight: 8,
      textStyle: {
        fontSize: 13,
        color: "#333",
      },
      borderRadius: 4,
      padding: [6, 10],
      shadowBlur: 4,
      shadowColor: "rgba(0, 0, 0, 0.15)",
      shadowOffsetX: 1,
      shadowOffsetY: 1,
    },
    tooltip: {},
    grid: {
      left: 0,
      right: 1,
      bottom: "20%",
      top: 60,
      containLabel: true,
    },
    color: ["#3498db", "#e74c3c"],
    xAxis: {
      data: chartData.categories,
      name: "",
      axisLabel: {
        rotate: 45, // 刻度标签倾斜角度
        fontSize: 10, // 刻度标签字体大小
      },
    },
    yAxis: [
      // 左侧Y轴（膀胱压力）
      {
        type: "value",
        name: "单位:mmH2O", // 压力单位
        show: true,
        nameTextStyle: {
          padding: [0, 0, 0, 40], // [上, 右, 下, 左]，正值表示向外扩
        },
      },
      // 右侧Y轴（实时尿量）
      {
        type: "value",
        name: "单位:ml/s", // 尿量单位
        show: true,
        position: "right", // 显示在右侧
      },
    ],
    series: [
      {
        name: "膀胱压力",
        type: "line",
        smooth: true,
        data: chartData.series1,
        yAxisIndex: 0, // 关联左侧Y轴
      },
      {
        name: "实时尿量",
        type: "line",
        smooth: true,
        data: chartData.series2,
        yAxisIndex: 1, // 关联右侧Y轴
      },
    ],
  });

  // 启动定时器，每秒添加一个数据点
  addDataPoint(data1, data2);
};

// 添加数据点的函数
const addDataPoint = (data1, data2) => {
  if (!myChart) return;

  // 生成新的x轴标签（使用时间戳）
  const now = new Date();
  const timeLabel = `${now.getHours()}:${now.getMinutes()}:${now.getSeconds()}`;

  // 生成随机数据
  const newData1 = Math.floor(Math.random() * 50) + 5;
  const newData2 = Math.floor(Math.random() * 100) + 5;

  // 添加新数据到末尾
  chartData.categories.push(timeLabel);
  chartData.series1.push(data1);
  chartData.series2.push(data2);

  // 保持数据点数量在10个以内
  const maxPoints = 10;
  if (chartData.categories.length > maxPoints) {
    chartData.categories.shift();
    chartData.series1.shift();
    chartData.series2.shift();
  }

  // 更新图表，不重新初始化
  myChart.setOption({
    xAxis: {
      data: chartData.categories,
    },
    series: [
      {
        data: chartData.series1,
      },
      {
        data: chartData.series2,
      },
    ],
  });
};

// 组件卸载时清除定时器
// 注意：在实际Vue组件中，应该在beforeUnmount钩子中调用
const clearChartTimer = () => {
  if (chartData.timer) {
    clearInterval(chartData.timer);
    chartData.timer = null;
  }
};

// 监听压力历史变化，自动更新图表
watch(
  [pressureHistory, volumeHistory],
  () => {
    // updateChart();
  },
  {
    deep: true,
  }
);

// 计算柱状图高度百分比
/* function getBarHeight(value) {
	  const maxValue = Math.max(...pressureHistory.value);
	  const minValue = Math.min(...pressureHistory.value);
	  const range = Math.max(maxValue - minValue, 10);
	  const heightPercent = ((value - minValue) / range) * 90 + 5;
	  return `${heightPercent}%`;
	} */
</script>

<style scoped>
/* 保留原CSS逻辑，适配uni-app */
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body,
page {
  font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
  background: linear-gradient(135deg, #f0f5ff, #e6f7ff);
  min-height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20px;
  color: #2c3e50;
}

.container {
  max-width: 600px;
  width: 100%;
  text-align: center;
}

.title {
  font-size: 28px;
  color: #2c3e50;
  margin-bottom: 25px;
  font-weight: 600;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.data-container {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 20px;
  padding: 30px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.15);
  margin-bottom: 25px;
}

.data-section {
  margin-bottom: 25px;
  padding-bottom: 20px;
  border-bottom: 1px solid #f0f0f0;
}

.data-label {
  font-size: 18px;
  color: #7f8c8d;
  margin-bottom: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.data-value {
  font-size: 48px;
  font-weight: 700;
  margin: 10px 0;
  transition: all 0.5s ease;
}

.pressure-value {
  color: #3498db;
}

.data-value.critical {
  color: #e74c3c;
  animation: pulse 1.5s infinite;
}

.unit {
  font-size: 20px;
  color: #7f8c8d;
  margin-bottom: 5px;
}

.unit sub {
  font-size: 14px;
  vertical-align: sub;
  color: #7f8c8d;
}

@keyframes pulse {
  0% {
    transform: scale(1);
  }

  50% {
    transform: scale(1.05);
  }

  100% {
    transform: scale(1);
  }
}

.status-container {
  display: flex;
  justify-content: space-between;
  margin-top: 20px;
}

.status {
  padding: 12px 15px;
  background: #f8f9fa;
  border-radius: 10px;
  font-size: 14px;
  color: #2c3e50;
  display: flex;
  align-items: center;
  flex: 1;
  margin: 0 5px;
}

.status-dot {
  display: inline-block;
  width: 12px;
  height: 12px;
  border-radius: 50%;
  margin-right: 8px;
  background-color: #e74c3c;
}

.status.connected .status-dot {
  background-color: #27ae60;
}

.footer {
  margin-top: 25px;
  color: #95a5a6;
  font-size: 13px;
  background: rgba(255, 255, 255, 0.8);
  padding: 12px;
  border-radius: 10px;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.05);
}

.chart-container {
  height: 250px;
  margin-top: 20px;
  position: relative;
}

/* .chart {
  width: 100%;
  height: 100%;
  border-radius: 8px;
  background: rgba(236, 240, 241, 0.5);
  position: relative;
  overflow: hidden;
}

.chart-line {
  position: absolute;
  bottom: 0;
  width: 100%;
  height: 2px;
  background: #bdc3c7;
}

.chart-data {
  position: absolute;
  bottom: 0;
  width: 100%;
  height: 100%;
  display: flex;
  align-items: flex-end;
}

.chart-bar {
  flex: 1;
  background: #3498db;
  margin: 0 1px;
  border-radius: 3px 3px 0 0;
  transition: height 0.5s ease;
}

.chart-label {
  position: absolute;
  bottom: -25px;
  width: 100%;
  display: flex;
  justify-content: space-between;
  font-size: 10px;
  color: #7f8c8d;
  padding: 0 5px;
}
 */
.data-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 15px;
  margin-top: 20px;
}

.data-card {
  background: #f8f9fa;
  border-radius: 12px;
  padding: 15px;
  text-align: center;
}

.card-label {
  font-size: 14px;
  color: #7f8c8d;
  margin-bottom: 5px;
}

.card-value {
  font-size: 24px;
  font-weight: 600;
}

.pressure-card .card-value {
  color: #3498db;
}

.flow-card .card-value {
  color: #27ae60;
}

.volume-card .card-value {
  color: #9b59b6;
}

.limit-card .card-value {
  color: #e67e22;
}
</style>
